package top.infopub.mgr.fia.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.dto.fia.FundsAppnDto;
import top.infopub.enums.fia.ApplyTypeEnum;
import top.infopub.enums.hr.PostGroupEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.fia.domain.FundsAppnDomain;
import top.infopub.mgr.fia.jsonvo.FundsAppnJsonVo;
import top.infopub.mgr.fia.service.FiaProcessManageService;
import top.infopub.mgr.fia.service.FundsAppnService;
import top.infopub.mgr.fia.vo.FundsAppnVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.model.fia.FundsAppn;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 资金拨付管理
 * @author wangw
 * @version 2020年3月17日
 * @see FundsAppnController
 * @since
 */
@Controller
@RequestMapping("/fundsAppn")
public class FundsAppnController extends GenericFlowController {

    @Autowired
    private FundsAppnService fundsAppnService;

    @Autowired
    private FiaProcessManageService fiaProcessManageService;

    /**
     * 资金拨付列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        List<Map<String, String>> applyType = ApplyTypeEnum.asList();
        request.setAttribute("applyType",applyType);
        return "fia/lay-fundsAppn-list";
    }

    /**
     * 资金拨付列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<FundsAppnDomain> queryDataByCondition(FundsAppnVo fundsAppnVo, ParamPage paramPage) {
        Page<FundsAppnDomain> page = new Page<FundsAppnDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (fundsAppnVo.getEndDate() != null) {
            fundsAppnVo.setEndDate(DateUtils.addDays(fundsAppnVo.getEndDate(), 1));
        }
        page = fundsAppnService.selectPageByDomainWhere(page, fundsAppnVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id SGUID
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        request.setAttribute("id", id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");//登录人和审批人一致使用该字段是否显示审核信息
        request.setAttribute("finFlag", "0");//指定财务人员进入审批页面必须填写财务信息
        if (StringUtils.isNotBlank(id)) {
            FundsAppn fundsAppn = fundsAppnService.selectByPrimaryKey(id);
            AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
            if (fundsAppn != null) {
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), fundsAppn.getProcessStatus())
                        || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), fundsAppn.getProcessStatus())) {
                    request.setAttribute("isAuditFlag", "0");
                }
                if (StringUtils.isNotBlank(fundsAppn.getProcessId()) && fundsAppn.getProcessId().length() > 10) {
                    request.setAttribute("processId", fundsAppn.getProcessId());
                    String auditTabFlag = fiaProcessManageService.checkShowAuditTab(fundsAppn.getProcessId(), vo);
                    if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), fundsAppn.getProcessStatus())
                            && StringUtils.equals("0", auditTabFlag)) {
                        request.setAttribute("isAuditFlag", "0");
                    }
                    //查询指定财务节点人员ID
                    List<String> finUserIdList = fiaProcessManageService.queryFinanceUserIdByProcessId(fundsAppn.getProcessId(), "-1", PostGroupEnum.FINANCE.getCode());
                    if (finUserIdList != null && finUserIdList.size() > 0) {
                        for (String finUserId : finUserIdList) {
                            if (StringUtils.isBlank(finUserId)) continue;
                            if (StringUtils.equals(vo.getId(), finUserId)) {
                                //当前待审批节点=当前登录人，需要编辑财务信息提交
                                request.setAttribute("finFlag", "1");//指定财务人员进入审批页面必须填写财务信息
                            }
                        }
                    }
                    request.setAttribute("auditTabFlag", auditTabFlag);
                }
            }
        }
        request.setAttribute("proCode", proCode);
        return "fia/lay-FundDisbursement-detail";
    }

    @RequestMapping("/queryDetail")
    @ResponseBody
    public RspVo queryDetail(String id) {
        FundsAppnJsonVo fundsAppnJson = fundsAppnService.queryDetailById(id);
        return RspVo.getSuccessResponse(fundsAppnJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String processId, String status, String auditMsg, FundsAppn fundsAppn) {
        //资金上交审批
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        List<String> finUserIdList = fiaProcessManageService.queryFinanceUserIdByProcessId(processId, "-1", PostGroupEnum.FINANCE.getCode());
        if (finUserIdList != null && finUserIdList.size() > 0) {
            for (String finUserId : finUserIdList) {
                if (StringUtils.isBlank(finUserId)) continue;
                if (StringUtils.equals(vo.getId(), finUserId)) {
                    //当前待审批节点=当前登录人，需要编辑财务信息提交
                    if (fundsAppn == null || fundsAppn.getActualAmt() == null
                            || fundsAppn.getActualDate() == null
                            || StringUtils.isBlank(fundsAppn.getBankName())
                            || StringUtils.isBlank(fundsAppn.getAccountNo())
                            || StringUtils.isBlank(fundsAppn.getReceiverName())
                            || StringUtils.isBlank(fundsAppn.getReceiverNo())
                            || StringUtils.isBlank(fundsAppn.getFinMemo())) {
                        return RspVo.getFailureResponse(401, "财务收款情况相关数据不能为空");
                    }
                    RspVo rspVo = fundsAppnService.modifyFinInfo(fundsAppn, vo, processId);
                    if (!rspVo.isSuccess()) return rspVo;
                    break;
                }
            }
        }
        fiaProcessManageService.auditProject(fundsAppn.getId(), processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑
     * @param bodyStr json数据
     * @param submitType 0=保存，1=提交
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        FundsAppnJsonVo fundsAppnJson = JSON.parseObject(str, FundsAppnJsonVo.class);
        FundsAppnDto fundsAppnDto = fundsAppnJson.getInfo();

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(fundsAppnJson.getFileAtt()!=null){
            String[] fileAtt = fundsAppnJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, fundsAppnDto.getId(), file);
                attachmentList.add(attachment);
            }
        }
        RspVo rspVo = fundsAppnService.edit(fundsAppnDto, attachmentList, submitType, vo);
        return rspVo;
    }
}
